<template>
    <div>
      <!-- 首页头部 -->
      <div class="fixed-top">
        <div class="top">
        <div class="top-left" @click="searchFalse" v-show="search"><i class="el-icon-arrow-left"></i></div>
        <div class="mall-top">垃圾分类</div>
        <div v-if="photo" class="top-right">
          <i class="el-icon-full-screen" @click="photo = false"></i>
        </div>
        <Scan v-else class="top-right"></Scan>
      </div>
      <!-- 搜索框 -->
      <div class="home-search">
          <el-input
            placeholder="请输入垃圾名称"
            v-model="input"
            class="seatch"
            @focus="searchTrue()"
            clearable>
            <el-button slot="append" icon="el-icon-search" @click="searchGarbage"></el-button>
          </el-input>
      </div>
    </div>
      <!-- 按照搜索框中内容出现的对应的值 ref对应于mounted里的Bscroll，使得该div里面的内容可以滚动 -->
      <div class="search-content" ref="search" v-show="input">
        <div class="search-item" v-for = "item of list" :key = "item.name">
          <div class="search-desc">{{item.name}}</div>
          <div class="search-right">{{item.type}}</div>
        </div>
        <div class="search-item" v-show="nonList">没有找到匹配数据</div>
      </div>
      <!-- 之前搜索的内容 -->
      <div class="search-values" ref="searchValue" v-show="search">
        <div class="search-top">
          <div class="search-history">查询历史</div>
          <div class="clear" @click="clearValue"><i class="el-icon-delete"></i>清空历史</div>
        </div>
        <div class="search-value" v-for="(value,index) in searchValue" :key="index">
          <div class="search-desc" @click="detail(value)">{{value}}</div>
          <div class="search-right" @click="delValue(value)">
            <i class="el-icon-circle-close"></i>
          </div>
        </div>
      </div>
      <!-- 垃圾介绍 -->
      <div class="home-introduce">
        <div class="introduce" @click="sortClick('/home/recycled')"><img src="/static/imgs/可回收垃圾.png" class="introduce-img" alt=""></div>
        <div class="introduce" @click="sortClick('/home/foodWaste')"><img src="/static/imgs/厨余垃圾.png" class="introduce-img" alt=""></div>
        <div class="introduce" @click="sortClick('/home/harmful')"><img src="/static/imgs/有害垃圾.png" class="introduce-img" alt=""></div>
        <div class="introduce" @click="sortClick('/home/other')"><img src="/static/imgs/其它垃圾.png" class="introduce-img" alt=""></div>
      </div>
      <!-- 测试题目 -->
      <div class="home-topic">
        <div class="topic-top">
          题目
          <div class="top-right">{{index}}/10</div>
        </div>
        <div class="topic-title">
          <div class="title">{{item.name}}</div>
          <div class="desc">属于以下那种分类？</div>
        </div>
        <div class="topic-choose">
          <div class="choose-title">请选择:</div>
          <div class="choose-button" v-for = "(item, index) of choose" :key = "item.id">
            <div class="_button" @click="submitChoose(item.desc, index)">{{item.desc}}</div>
          </div>
        </div>
        <div class="topic-bottom">
          <el-button @click="preTitle">上一题</el-button>
          <el-button class="bottom-right" @click="nextTitle" v-show="flag">下一题</el-button>
          <el-button class="bottom-right" @click="submitAnswer" v-show="!flag">提 交</el-button>
        </div>
        <div class="home-tips" v-show="showT">
          <div class="tips-desc">此次答题答对{{score}}题，共获得{{score}}个积分</div>
          <div class="tips-choose">
            <el-button class="answer-left" @click="submitRefresh">确定</el-button>
            <!-- <el-button class="choose-right" @click="tip=false">取消</el-button> -->
          </div>
      </div>
      </div>
      <!-- 错题库 -->
      <div class="home-bottom" @click="errorClick">错题库</div>
      <!-- 当已经参与答题时，点击其他地方，则出现此提示 -->
      <div class="home-tips" v-show="tip">
        <div class="tips-desc">此操作后已作答题目将作废, 是否继续?</div>
        <div class="tips-choose">
          <el-button class="choose-left" @click="enter">确定</el-button>
          <el-button class="choose-right" @click="tip=false">取消</el-button>
        </div>
      </div>
      <Menu></Menu>
    </div>
</template>

<script>
import Menu from './common/Menu'
import Scan from './home/scan'
import axios from 'axios'
import Bscroll from 'better-scroll'
import { garbageMixin } from '../utils/mixin'
import { getLocalStorage, setLocalStorage } from '../utils/localStorage'

export default {
  mixins: [garbageMixin],
  components: {
    Menu,
    Scan
  },
  data () {
    return {
      values: [],
      input: '',
      photo: true,
      list: [],
      nonList: false,
      timer: null,
      searchValue: [],
      search: false,
      index: 1,
      item: '',
      titles: [],
      count: 0,
      errors: [],
      score: 0,
      flag: true,
      tip: false,
      showT: false,
      path: '',
      id: '',
      intergration: '',
      choose: [{
        id: '01',
        desc: '可回收垃圾'
      }, {
        id: '02',
        desc: '厨余垃圾'
      }, {
        id: '03',
        desc: '有害垃圾'
      }, {
        id: '04',
        desc: '其他垃圾'
      }]
    }
  },
  methods: {
    // searchTrue，searchFalse判断input是否获得焦点及将input置为空
    searchTrue () {
      this.search = true
    },
    searchFalse () {
      this.search = false
      this.input = ''
    },
    // 将搜索内容存入内存
    searchGarbage () {
      // 将搜索历史存入session
      let input = this.input
      let inputName = 'userName' + input
      sessionStorage.setItem(inputName, input)
      this.searchValue = []
      var storage = window.sessionStorage
      for (let i = 0; i < storage.length; i++) {
        if (storage.key(i).indexOf('userName') === 0) {
          var key = storage.key(i)
          var value = storage.getItem(key)
          this.searchValue.push(value)
        }
      }
      // 查询符合搜索的垃圾种类
      if (input !== '') {
        this.list = []
        let data = 'name=' + input
        console.log(data)
        this.$axios.get('/rubbish/search?name=' + input)
          .then(res => {
            // 判断数据库里是否有所搜索的数据
            if (res.data.code === 50001) {
              this.nonList = true
            } else {
              this.list = res.data.data
              if (this.searchValue.length < 30) {
                setLocalStorage('userIntergration', this.intergration + 1)
                this.intergration = getLocalStorage('userIntergration')
                console.log(this.searchValue.length, this.intergration, 'input')
              }
              console.log(res, 'res rubbish')
            }
          })
          .catch(function (error) {
            console.log(error, 'error rubbish')
          })
      }
    },
    // 点击搜索结果进入搜索页面,并将搜索内容存入本地内存
    detail (value) {
      console.log('点击搜索框')
      // 将值赋给input框
      this.input = value
      this.$axios.get('/rubbish/search?name=' + this.input)
        .then(res => {
          if (res.status === 404) {
            console.log('404 error')
          } else {
            this.list = res.data.data
            console.log(res, 'ress rubbish')
            this.$nextTick(() => {
              this.scroll = new Bscroll(this.$refs.search)
            })
            // 判断数据库里是否有所搜索的数据
            if (res.data.code === 50001) {
              this.nonList = true
            }
          }
        })
        .catch(function (error) {
          console.log(error, 'error h')
        })
    },
    // 判断进入哪个垃圾分类页面
    sortClick (tag) {
      if (this.titles[0].choose !== undefined) {
        this.tip = true
        this.path = tag
      } else {
        this.$router.push(tag)
      }
    },
    // 上一题
    preTitle () {
      this.item = this.titles[this.index - 2]
      // 判断该题目是否为第一题
      if (this.index === 1) {
        this.$message({
          message: '已经没有了上一题，请点击下一题',
          type: 'warning'
        })
        console.log(this.index)
      } else {
        this.index = this.index - 1
        // 获取选项，先将选项颜色都置为白色，然后在判断该题选了哪一个选项
        let div = document.getElementsByClassName('_button')
        for (let i = 0; i < 4; i++) {
          div[i].style.background = 'white'
        }
        // 判断上一题的选项
        if (this.item.choose === '可回收垃圾') {
          div[0].style.background = 'skyblue'
        } else if (this.item.choose === '厨余垃圾') {
          div[1].style.background = 'skyblue'
        } else if (this.item.choose === '有害垃圾') {
          div[2].style.background = 'skyblue'
        } else if (this.item.choose === '其他垃圾') {
          div[3].style.background = 'skyblue'
        } else {
          for (let i = 0; i < 4; i++) {
            div[i].style.background = 'white'
          }
        }
      }
    },
    // 下一题
    nextTitle () {
      this.item = this.titles[this.index]
      // console.log(this.item.title)
      this.index = this.index + 1
      console.log(this.index, 'index')
      if (this.index === 10) {
        this.flag = false
      }
      let div = document.getElementsByClassName('_button')
      for (let i = 0; i < 4; i++) {
        div[i].style.background = 'white'
      }
      if (this.item.choose === '可回收垃圾') {
        div[0].style.background = 'skyblue'
      } else if (this.item.choose === '厨余垃圾') {
        div[1].style.background = 'skyblue'
      } else if (this.item.choose === '有害垃圾') {
        div[2].style.background = 'skyblue'
      } else if (this.item.choose === '其他垃圾') {
        div[3].style.background = 'skyblue'
      } else {
        for (let i = 0; i < 4; i++) {
          div[i].style.background = 'white'
        }
      }
    },
    // 选择题目答案 e为垃圾类型 count为该垃圾类型所处位置
    submitChoose (e, count) {
      console.log(e, count, 'click', this.item)
      this.titles[this.index - 1].choose = e
      let div = document.getElementsByClassName('_button')
      // console.log(div[index].style.background, 'style')
      if (div[count].style.background === 'skyblue none repeat scroll 0% 0%') {
        div[count].style.background = 'white'
      } else {
        for (let i = 0; i < div.length; i++) {
          div[i].style.background = 'white'
        }
        div[count].style.background = 'skyblue'
        // console.log(div.length, 'length')
      }
    },
    // 提交10道题目
    submitAnswer () {
      this.errors = []
      for (let i = 0; i < 10; i++) {
        // console.log(this.titles[i].type === this.titles[i].choose, this.titles[i].choose, this.score, 'this.answer[i]')
        if (this.titles[i].type === this.titles[i].choose) {
          this.score = this.score + 1
          // console.log(this.titles[i].type, this.titles[i].choose, this.score, this.errors, 'fffff')
        } else {
          this.errors.push(this.titles[i].id)
        }
      }
      let error = this.errors
      let sessionId = getLocalStorage('sessionId')
      console.log({list: error}, sessionId, 'this.$qs.stringify(error)')
      this.$axios.post('/rubbish/wrongQuestion', {list: error}, {headers: {'Content-Type': 'application/json', 'sessionId': sessionId}})
        .then((res) => {
          console.log(res, 'ressssssss')
          if (res.data.code === 1) {
            this.flag = true
            this.showT = true
            this.index = 1
            setLocalStorage('userIntergration', this.intergration + this.score)
          }
        })
    },
    // 错题库
    errorClick () {
      if (this.titles[0].choose !== undefined) {
        this.tip = true
        this.path = '/home/error'
      } else {
        this.$router.push('/home/error')
      }
    },
    // 删除内存中的该键值对
    delValue (value) {
      let key = 'userName' + value
      sessionStorage.removeItem(key)
      var storage = window.sessionStorage
      this.searchValue = []
      for (let i = 0; i < storage.length; i++) {
        if (storage.key(i).indexOf('userName') === 0) {
          var k = storage.key(i)
          var v = storage.getItem(k)
          this.searchValue.push(v)
        }
      }
    },

    // 从后台获取题目
    getTitle () {
      axios({
        methods: 'get',
        url: '/rubbish'
      }).then((res) => {
        if ((res.status === 200) && res.data.data) {
          console.log(res)
          res = res.data.data
          this.titles = res
          this.values = res
          this.item = this.titles[0]
        }
      })
    },

    // 删除本地所有的保存信息
    clearValue () {
      sessionStorage.clear()
      this.searchValue = []
    },
    // 选择确定后，进入相对应页面
    enter () {
      this.$router.push(this.path)
    },

    // 确定后重新刷新题目界面
    submitRefresh () {
      this.showT = false
      this.getTitle()
    }
  },
  watch: {
    // 监控输入框的实时变化
    input () {
      // 节流函数：当持续触发事件时，保证在一定时间内只调用一次事件处理函数，意思就是说，假设一个用户一直触发这个函数，且每次触发小于既定值，函数节流会每隔这个时间调用一次
      if (this.timer) {
        clearTimeout(this.time)
      }
      if (!this.input) {
        this.list = []
        this.nonList = false
        // return
      }

      // 注册鼠标点击enter搜索事件
      // let text= document.getElementsByClassName("seatch")
      //  key.onkeyup = f  //注册keyup事件处理函数
      //  f (){
      //    if (event.keyCode==13) {
      //      this.searchGarbage()
      //    }
      //  }

      // this.timer = setTimeout(() => {
      //   const result = []
      //   for (let i = 0; i < this.values.length; i++) {
      //     if (this.values[i].title.indexOf(this.input) > -1) {
      //       result.push(this.values[i])
      //       // console.log(result, 'result')
      //     }
      //   }
      //   this.list = result
      //   console.log(this.list, 'list')
      // }, 100)
    }
  },
  mounted () {
    console.log(this.userPhone, 'userPhone1')
    // 从后台获取题目
    this.getTitle()

    // 获取存储在本地会话里的信息
    var storage = window.sessionStorage
    for (let i = 0; i < storage.length; i++) {
      // console.log(storage.key(i).indexOf('userName'))
      if (storage.key(i).indexOf('userName') === 0) {
        var key = storage.key(i)
        var value = storage.getItem(key)
        this.searchValue.push(value)
      }
    }
    // this.$refs.search 使得ref中对应的search所在的div内的内容能够滚动。
    this.$nextTick(() => {
      this.scroll = new Bscroll(this.$refs.searchValue)
    })

    // 获取本地存储的用户信息
    this.id = getLocalStorage('id')
    this.intergration = getLocalStorage('userIntergration')
  }
}
</script>

<style lang="scss" scoped>
@import "../assets/styles/global";
.fixed-top {
  height: 110px;
  .top{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 9;
    display: flex;
    width: 100%;
    height: 35px;
    line-height: 35px;
    text-align: center;
    font-size: 17px;
    background: skyblue;
    .top-left{
      position: fixed;
      top: 2px;
      left: 2%;
      font-size: 28px;
    }
    .mall-top{
      flex: 1;
      margin-left: 30px;
    }
    .top-right{
      font-size: 30px;
      font-weight: 700px;
      margin-right: 10px;
      width: 30px;
    }
  }
  .home-search{
    position: fixed;
    top: 35px;
    left: 0;
    right: 0;
    display: flex;
    width: 100%;
    background: skyblue;
    .seatch{
      box-sizing: border-box;
      width: 96%;
      margin: 2%;
      padding: 10px 0 5px 5px;
    }
  }
}
  .search-content{
    z-index: 10000;
    overflow: auto;
    position: fixed;
    top: 110px;
    left: 0;
    right: 0;
    bottom: 0;
    background: #eee;
    .search-item{
      display: flex;
      margin-bottom: 1%;
      height: 30px;
      line-height: 30px;
      padding-left: 5px;
      background: #fff;
      color: #666;
      border-bottom: #666;
      .search-desc{
        flex: 1;
        font-size: 14px;
      }
      .search-right{
        float: right;
        padding: 0 8px;
        font-size: 14px;
      }
    }
  }
  .search-values{
    z-index: 9999;
    overflow: auto;
    position: fixed;
    top: 100px;
    left: 0;
    right: 0;
    bottom: 0;
    background: #eee;
    .search-top{
      margin: 8px;
      height: 15px;
      line-height: 15px;
      .search-history{
        float: left;
        padding-left: 5px;
        color: #b4b6b7;
      }
      .clear{
        float: right;
        padding-right: 5px;
      }
    }
    .search-value{
      display: flex;
      width: 96%;
      height: 35px;
      line-height: 35px;
      margin: 8px auto;
      padding-left: 10px;
      background: white;
      .search-desc{
        flex: 1;
        font-size: 14px;
      }
      .search-right{
        float: right;
        padding: 0 8px;
        font-size: 18px;
      }
    }
  }
  .home-introduce{
    display: flex;
    width: 96%;
    height: 110px;
    margin: 10px 2%;
    background: white;
    border-radius: 10px;
    .introduce{
      width: 22%;
      margin: 10px 5px;
      overflow: hidden;
      border-radius: 8px;
      .introduce-img{
        width: 100%;
        height: 100%;
        margin: auto;
      }
    }
  }
  .home-topic{
    width: 96%;
    margin: 10px 2%;
    padding: 10px 0;
    background: white;
    border-radius: 10px;
    .topic-top{
      padding: 10px 15px;
      .top-right{
        float: right;
        top: 0;
        right: 0;
      }
    }
    .topic-title{
      height: 50px;
      text-align: center;
      .title{
        font-size: 20px;
        padding-bottom: 10px;
      }
    }
    .topic-choose{
      padding: 5px 15px;
      .choose-button{
        margin: 5px auto;
        ._button{
          width:100%;
          height: 40px;
          line-height: 40px;
          text-align: center;
          border: 1px solid skyblue;
          border-radius: 8px;
          background: white;
        }
      }
    }
    .topic-bottom{
      position: relative;
      padding: 5px 15px;
      .bottom-right{
        position: absolute;
        right: 15px
      }
    }
  }
  router-link{
    text-decoration: none;
  }
  .home-bottom{
    width: 96%;
    height: 50px;
    line-height: 50px;
    margin: 10px 2%;
    background: white;
    border-radius: 10px;
    margin-bottom: 60px;
    font-size: 18px;
    text-align: center;
  }
  .home-tips{
    position: fixed;
    top: 350px;
    left: 2%;
    z-index: 1;
    width: 96%;
    height: 120px;
    background: white;
    border: 1px solid #DCDFE6;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    .tips-desc{
      height: 50px;
      line-height: 50px;
      text-align: center;
      font-size: 16px;
      padding-top: 10px;
    }
    .tips-choose{
      height: 50px;
      .choose-left{
        float: left;
        margin-left: 10%;
      }
      .choose-right{
        float: right;
        margin-right: 10%;
      }
      .answer-left{
        float: left;
        margin-left: 39%;
      }
    }
  }
</style>
